package com.thh.filesystem.service;

import com.alibaba.fastjson.JSON;

import com.thh.filesystem.dao.FileSystemRepository;
import com.thh.filesystem.domain.FileSystem;
import com.thh.filesystem.domain.response.FileSystemCode;
import com.thh.filesystem.domain.response.UploadFileResult;
import com.thh.filesystem.exception.ExceptionCast;
import com.thh.filesystem.model.response.CommonCode;
import com.thh.filesystem.uitl.DownloadUtil;
import com.thh.filesystem.uitl.FastDFSClient;
import com.thh.filesystem.uitl.FastDFSClient2;
import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.util.Optional;


/**
 * @author Administrator
 * @version 1.0
 **/
@Service
public class FileSystemService {



    @Autowired
    FileSystemRepository fileSystemRepository;

    @Autowired
    FastDFSClient fastDFSClient;


    //上传文件
    public UploadFileResult upload(MultipartFile multipartFile,
                                   String filetag,
                                   String businesskey,
                                   String metadata){
        if(multipartFile ==null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        //第一步：将文件上传到fastDFS中，得到一个文件id
        //String fileId = fastDFSClient.fdfsUpload(multipartFile);

        String fileId = "";
        String[] uploadResult = FastDFSClient2.uploadFile(multipartFile);
        fileId =  uploadResult[0] + "/" + uploadResult[1];
        String path = FastDFSClient2.getTrackerUrl()+"/"+fileId;
        if(StringUtils.isEmpty(fileId)){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        //第二步：将文件id及其它文件信息存储到mongodb中。
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);     //文件id
        fileSystem.setFilePath(fileId);   //文件路径
        fileSystem.setFileSize(multipartFile.getSize());//文件大小
        //fileSystem.setFileType(getPostfix(multipartFile));//文件后缀
        fileSystem.setFileType(multipartFile.getContentType());//文件类型
        fileSystem.setFiletag(filetag);   //文件标签
        //用户id写死 暂时没有集成
        fileSystem.setUserId("1");
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFileName(multipartFile.getOriginalFilename());
        fileSystem.setFileType(multipartFile.getContentType());
        if(StringUtils.isNotEmpty(metadata)){
            try {
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }


    public FileSystem findFileSystemById(String id){
        Optional<FileSystem> optional = fileSystemRepository.findById(id);
        if (optional.isPresent()){
            return  optional.get();
        }
        return null;
    }
    public void download(String path, HttpServletResponse response) {

        FileSystem fileSystem = findFileSystemById(path);
        if (fileSystem==null){
            ExceptionCast.cast(FileSystemCode.FS_FILE_NOTEXISTS);//文件不存在
        }

        try {
            byte[] bytes = FastDFSClient2.downFile(path);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(bytes);
            DownloadUtil.download(bos,response,fileSystem.getFileName());
        }catch (Exception e){
            ExceptionCast.cast(FileSystemCode.FS_DOWNLOAD_FAIL);
        }
    }


    public void download2(String group_name, String remote_filename,HttpServletResponse response) {

        FileSystem fileSystem = findFileSystemById(group_name+"/"+remote_filename);
        if (fileSystem==null){
            ExceptionCast.cast(FileSystemCode.FS_FILE_NOTEXISTS);//文件不存在
        }

        try {
            byte[] bytes = FastDFSClient2.downFile(group_name,remote_filename);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(bytes);
            DownloadUtil.download(bos,response,fileSystem.getFileName());
        }catch (Exception e){
            ExceptionCast.cast(FileSystemCode.FS_DOWNLOAD_FAIL);
        }
    }

    public void urlDownload(String url, HttpServletResponse response) {



    }
}
